#include<iostream>

using std::cout;
using std::endl;
#include <fcntl.h>           /* For O_* constants */
#include <sys/stat.h>        /* For mode constants */
#include <semaphore.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/mman.h>


#define FILE_MODE S_IRUSR|S_IWUSR

int count = 0;
int max(int a, int b)
{
    return (a > b) ? a : b;
}

#include <unistd.h>
int main(int argc, char** argv)
{

    if(argc != 4){
        cout << "usage: test1 <pathname> <filesize> <mmapsize>" << endl;
    }
    

    int filesize = atoi(argv[2]);
    int mmapsize = atoi(argv[3]);
    

    int fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, FILE_MODE);
    lseek(fd, filesize - 1, SEEK_SET);
    write(fd, "", 1);

    int* ptr = (int*)mmap(NULL, mmapsize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    
    close(fd);
    
    int pagesize = sysconf(_SC_PAGESIZE);
    cout << "PAGESIZE = " << pagesize << endl;
    
    int i = 0;
    for(i = 0; i < max(filesize, mmapsize); i += pagesize){
        cout << "ptr[" << i << "] = " << ptr[i] << endl;
        ptr[i] = 1;
        cout << "ptr[" << i + pagesize -1 << "] = " << ptr[i] << endl;
        ptr[i + pagesize - 1] = 1;
    }

    cout << "ptr[" << i << "] = " << ptr[i] << endl;
    exit(0);
}
